
import Koa from 'koa'
import views from 'koa-views'
import { scheduleJob } from 'node-schedule'
import path from 'path'
import { createMogodb } from './db'
import { ProxyModel } from './model'
import { createView } from './view'
import { proxyServe } from './proxy-serve'
import { program } from 'commander'
import { ProxyInterface } from './etl'
import { ProxyListsImpl } from './proxy-serve/proxy-lists'



program
    .requiredOption('--config <configName>', 'Select configuration file. example --config=testConfig start test env')
    .option(`--uri [uri]`, 'Specify the connection address of the database', 'mongodb://172.16.0.90:27017')
    .option(`-p,--port [port]`, `web port`, '3000')
    .parse()

const options = program.opts();
const config = require(`../etc/${options.config}`)
if (options.uri) config.uri = options.uri
if (options.port) config.port = options.port
// //web服务
export async function serve(config: any) {

    const { tpl, port } = config
    const app = new Koa()
    const cwd = process.cwd()
    app.use(views(path.join(cwd, tpl), {
        extension: 'ejs'
    }))
    const view = await createView(config)
    app.use(view)

    app.listen(port, () => {
        console.log(`服务启动，监听端口${port}`)
    })
}

//检查数据库中代理是否失效
export async function update(config: any) {
    scheduleJob("* * 0/12 * * ? *", async () => {
        // await updateService.updateProxy()
    })
}


//代理获取和添加
export async function proxy(config: any) {
    const client = await createMogodb<ProxyInterface>(config, 'proxyLists')
    const childClient = await createMogodb<ProxyInterface>(config, 'childLists')
    await proxyServe(config, client, childClient)
    scheduleJob("* * 0/3 * * ? *", async () => {
        await proxyServe(config, client, childClient)
    })
}

update(config)
proxy(config)

